var request = require('../../utils/request');

Page({
  data: {
    second: 60,
    selected: true,
    selected1: false,
    testNum:"",
  },

  getNum: function (e) {
    //获取验证码
    var id = wx.getStorageSync('sessionId');
    var num = wx.getStorageSync('mobile');
    var data = {
      'self:sms:generate':{
        'sms_type':'verification',
        'mobile':num,
        'wx_session':id
      }
    }
    request.post({
      path: '/wxapp_api/api'
    },data)
      .then(function (res) {
        var retData = res['self:sms:generate'];
        if (retData.ret != 0) {
          wx.showModal({
            content: retData.msg,
            showCancel:false
          })
          return;
        }
      });
    this.setData({
      selected: false,
      selected1: true,
    });
    countdown(this);
  },

  changeTest: function(e){
    var test = e.detail.value;
    this.setData({
      testNum:test
    })
  },

  onLoad: function () {
    this.setData({
      selected: false,
      selected1: true,
    });
    countdown(this);
  },

  gopage: function(){
    if (this.data.testNum == ""){
      wx.showModal({
        content: "请先输入验证码",
        showCancel: false
      });
      return;
    } else if (this.data.testNum.length < 6){
      wx.showModal({
        content: "验证码不正确",
        showCancel: false
      });
      return;
    }
    var id = wx.getStorageSync('sessionId');
    var num = wx.getStorageSync('mobile');
    var test = this.data.testNum;
    var data = {
      'self:sms:validate':{
        'sms_type':'verification',
        'mobile':num,
        'code':test,
        'wx_session':id
      }
    }
    request.post({
      path: '/wxapp_api/api'
    },data)
      .then(function (res) {
        var retData = res['self:sms:validate'];
        if (retData.ret != 0) {
          wx.showModal({
            content: retData.msg,
            showCancel:false
          })
          return;
        }else{
          var url = "../has-link3/has-link3"
          wx.navigateTo({
            url: url
          })
        }
      });
    
  },

  goback: function(){
    wx.navigateBack({
      delta : 1
    })
  },

  gohome: function(){
    wx.switchTab({ 
      url: '../new-index/index', 
      success: function (e) { 
        var page = getCurrentPages().pop(); 
        if (page == undefined || page == null) return; 
        page.onLoad(); 
      } 
    })
  }
  
});

function countdown(that) {
  var second = that.data.second;
  if (second == 0) {
    // console.log("Time Out...");
    that.setData({
      selected: true,
      selected1: false,
      second: 60,
    });
    return;
  }
  var time = setTimeout(function () {
    that.setData({
      second: second - 1
    });
    countdown(that);
  }
    , 1000)
}
